﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Doan.Forum.Models;

namespace Doan.Forum.Controllers
{
    public class PMessageController : Controller
    {
        private static DoAnForumEntities db = new DoAnForumEntities();
        //
        // GET: /PMessage/

        public ActionResult Index()
        {
            var crrUser = db.aspnet_Users.SingleOrDefault(x => User.Identity.Name.Equals(x.UserName));

            //Get Inbox
            var hasMessage = db.PMessages.Where(x => (x.ToUserId == crrUser.UserId)&&(x.Deleted==1||x.Deleted==null));
            if (hasMessage.Any())
            {
                var inbox = (hasMessage.Join(db.aspnet_Users, tab1 => tab1.FromUserId, tab2 => tab2.UserId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.PMessageID,
                                               tab1.Flags,
                                               tab2.UserName,
                                               tab1.Subject,
                                               tab1.Created
                                           })).ToList();
                var listInbox = new List<InboxModel>();
                foreach (var item in inbox)
                {
                    var inboxModel = new InboxModel();
                    inboxModel.MessageId = item.PMessageID;
                    inboxModel.FromUserName = item.UserName;
                    inboxModel.Subject = item.Subject;
                    inboxModel.CreateDate = item.Created;
                    inboxModel.UnRead = item.Flags;
                    listInbox.Add(inboxModel);
                }
                ViewBag.listInbox = listInbox;
            }
            else
            {
                ViewBag.listInbox = null;
            }

            //Get Sent Item
            hasMessage = db.PMessages.Where(x => (x.FromUserId == crrUser.UserId) && (x.Deleted==null||x.Deleted!=1));
            if (hasMessage.Any())
            {
                var inbox = (hasMessage.Join(db.aspnet_Users, tab1 => tab1.ToUserId, tab2 => tab2.UserId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.PMessageID,
                                               tab2.UserName,
                                               tab1.Subject,
                                               tab1.Created
                                           })).ToList();
                var listsentItem = new List<SentItemModel>();
                foreach (var item in inbox)
                {
                    var sentitemModel = new SentItemModel();
                    sentitemModel.MessageId = item.PMessageID;
                    sentitemModel.ToUserName = item.UserName;
                    sentitemModel.Subject = item.Subject;
                    sentitemModel.CreateDate = item.Created;
                    listsentItem.Add(sentitemModel);
                }
                ViewBag.listsentItem = listsentItem;
            }
            else
            {
                ViewBag.listsentItem = null;
            }
            return View();
        }

        public ActionResult ViewMessage(int id)
        {
            var pMessage = db.PMessages.SingleOrDefault(x => x.PMessageID == id);
            var fromUserName = db.aspnet_Users.SingleOrDefault(x => x.UserId == pMessage.FromUserId).UserName;
            var viewMessage = new ViewMessageModel();
            viewMessage.Subject = pMessage.Subject;
            viewMessage.FromUserName = fromUserName;
            viewMessage.SendDate = pMessage.Created;
            viewMessage.Content = pMessage.Body;
            viewMessage.MessageId = pMessage.PMessageID;

            pMessage.Flags = false;
            db.SaveChanges();
            return View(viewMessage);
        }

        [HttpGet]
        public ActionResult CreateMessage()
        {
            ViewBag.Error = null;
            return View();
        }

        [HttpGet]
        public ActionResult RepliMessage(int id)
        {
            ViewBag.Error = null;
            var replims = db.PMessages.SingleOrDefault(x => x.PMessageID == id);
            var toUserName = db.aspnet_Users.SingleOrDefault(x => x.UserId == replims.FromUserId).UserName;
            var ms = new CreatePMessageModel();
            ms.Subject = "Re: " + replims.Subject;
            ms.ToUserName = toUserName;
            return PartialView("CreateMessage",ms);
        }

        [HttpGet]
        public ActionResult SendMessage(string userName)
        {
            ViewBag.Error = null;
            var ms = new CreatePMessageModel();
            ms.ToUserName = userName;
            return PartialView("CreateMessage", ms);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateMessage(CreatePMessageModel model)
        {
            var toUser = db.aspnet_Users.SingleOrDefault(x => model.ToUserName.Equals(x.UserName));
            if (toUser != null)
            {
                PMessage pMessage = new PMessage();
                pMessage.Created = DateTime.Now;
                pMessage.Subject = model.Subject;
                pMessage.Body = model.Content;
                pMessage.Flags = true;
                var fromUser = db.aspnet_Users.SingleOrDefault(x => User.Identity.Name.Equals(x.UserName));
                pMessage.FromUserId = fromUser.UserId;
                pMessage.ToUserId = toUser.UserId;
                db.PMessages.AddObject(pMessage);
                db.SaveChanges();
                ViewBag.Error = null;
                ViewBag.SuccessP = "Thư của bạn đã được gửi đi";
            }
            else
            {
                ViewBag.Error = "Người nhận không tồn tại";
            }
            return View();
        }

        public ActionResult Delete(int id)
        {
            var DeleteItem = db.PMessages.SingleOrDefault(x => x.PMessageID == id);
            var crrUser = db.aspnet_Users.SingleOrDefault(x => User.Identity.Name.Equals(x.UserName));

            try
            {
                if(crrUser.UserId==DeleteItem.FromUserId)
                {
                    if (DeleteItem.Deleted == null)
                    {
                        DeleteItem.Deleted = 1;
                        db.SaveChanges();
                    }
                    else if (DeleteItem.Deleted==2)
                    {
                        db.PMessages.DeleteObject(DeleteItem);
                        db.SaveChanges();
                    }
                }
                else
                {
                    if (DeleteItem.Deleted == null)
                    {
                        DeleteItem.Deleted = 2;
                        DeleteItem.Flags = false;
                        db.SaveChanges();
                    }
                    else if (DeleteItem.Deleted == 1)
                    {
                        db.PMessages.DeleteObject(DeleteItem);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return RedirectToAction("Index");
        }

    }
}
